from django import forms
from core.models import KnowledgePoint

class KnowledgePointForm(forms.ModelForm):
    class Meta:
        model = KnowledgePoint
        fields = ['chapter', 'name', 'description', 'order']
        widgets = {
            'chapter': forms.Select(attrs={'class': 'form-select'}),
            'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入知识点名称'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 3, 'placeholder': '请输入知识点描述'}),
            'order': forms.NumberInput(attrs={'class': 'form-control', 'min': 0, 'placeholder': '排序号'})
        }
        labels = {
            'chapter': '所属章节',
            'name': '知识点名称',
            'description': '知识点描述',
            'order': '排序号'
        }

    def clean_name(self):
        name = self.cleaned_data.get('name')
        chapter = self.cleaned_data.get('chapter')
        instance = self.instance

        # 检查同章节下是否存在同名知识点（排除当前编辑的知识点）
        if instance and instance.pk:
            exists = KnowledgePoint.objects.filter(chapter=chapter, name=name).exclude(pk=instance.pk).exists()
        else:
            exists = KnowledgePoint.objects.filter(chapter=chapter, name=name).exists()

        if exists:
            raise forms.ValidationError('该章节下已存在同名知识点')
        return name